(ns util.cmd.rc
  (:use util.os
        util.file)
  (:require clojure.string))

(defn- linux-search-path []
  [(System/getProperty "user.home")])

(defn- windows-search-path []
  [(System/getenv "USERPROFILE")
   (System/getenv "APPDATA")])

(defn- search-file [name]
  (->> (if (windows?) (windows-search-path) (linux-search-path))
    (map #(file-join % name))
    (filter file-exists?)
    first))

(defn- search-files [names]
  (first (map search-file names)))

(defn- parse-option [s]
  (when-let [[_ k v] (re-matches #"--?(\w[\w-]*)(?:=(.*))?" s)]
    (if v
      [(keyword k) v]
      (if-let [[_ k] (re-matches #"no-(.+)" k)]
        [(keyword k) false]
        [(keyword k) true]))))

(defn- parse-options [txt]
  (->> txt
    clojure.string/split-lines
    (keep parse-option)
    (into {})))

(defn load-rc [name]
  (let [name (clojure.string/replace name #"^\." "")
        names [(str "." name) (str "_" name) name]
        path (search-files names)]
    (when (and path (file-exists? path))
      (parse-options (slurp path)))))

